import React from "react";
import { Breadcrumb } from "antd";
import { Link, useLocation } from "react-router-dom";
import menus from "@/routers/menus";

const breadcrumbNameMap = {};
const getBreadCrumb = (menus) => {
  menus.forEach((menu) => {
    if (menu.children) {
      breadcrumbNameMap[menu.key] = menu.label;
      getBreadCrumb(menu.children);
    } else {
      breadcrumbNameMap[menu.key] = menu.label;
    }
  });
};
getBreadCrumb(menus);

const AppBreadCrumb = () => {
  const location = useLocation();
  const pathSnippets = location.pathname.split("/").filter((i) => i);

  const extraBreadcrumbItems = pathSnippets.map((_, index) => {
    const url = `/${pathSnippets.slice(0, index + 1).join("/")}`;
    return {
      key: url,
      title: <Link to={url}>{breadcrumbNameMap[url]}</Link>,
    };
  });

  const breadcrumbItems = [
    {
      title: "当前所在",
    },
    {
      title: <Link to="/">主页</Link>,
      key: "home",
    },
  ].concat(extraBreadcrumbItems);

  return (
    <div className="demo">
      <Breadcrumb separator=">" items={breadcrumbItems} />
    </div>
  );
};

export default AppBreadCrumb;
